package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.JSoupUtils;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;

public class CrnttNewsAnalyse implements AnalyseNews {

	private static final String[] regex={
		"http://www.crntt.com/doc/[0-9_]+.html" ,
		"http://www.crntt.com/doc/[0-9/]+/[0-9]+.html\\?coluid=[0-9]+&kindid=[0-9]+&docid=[0-9]+&mdate=[0-9]+" ,
		};

	
	public boolean isDetailPage(String url) {
		for (int i=0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return false;
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	
	public boolean isNeedUpdate() {
		return false;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta news=new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();
		if (!isDetailPage(url)) {
		}

		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);
		title=doc.select("font[color=#000000] strong").text();
		if(StringUtils.isBlank(title)){
					title=doc.select("title").text();
					if (title.contains("－")) {
						title=StringUtils.substringBefore(title, "－");
					}
		}
		date=DateUtils.matchDate(doc.select("html body div table tbody tr td table tbody tr td table tbody tr td[align=center]").text());
		if (date == null) {
			date=JSoupUtils.matchDate(doc, "www.CRNTT.com");
		}
		author=JSoupUtils.matchAuthor(doc, "来源:");
		content=HtmlCleaner.getContentHtml(url,doc.select("td#zoom"));
		news.setUrl(url);
		news.setTitle(title);
		news.setContent(content);
		news.setAuthor(author);
		news.setDate(date);
		return news;
	}

	public static void main(String[] args) {
		CrnttNewsAnalyse test=new CrnttNewsAnalyse();

		String url="http://www.crntt.com/doc/4_16_103380783_1_0912083724.html";
		url=UrlArgumentTop.FromatUrl(url);
		System.out.println(url);
		UrlMeta meta=CrawlHTML.responseToURL(url);
		System.out.println(test.isDetailPage(url));
		NewsMeta parserHtml=test.parserHtml(meta);
		System.out.println(parserHtml);
	}

}
